% rebase('layout.tpl', title=title, year=year, jsfiles=['jquery-1.10.2.min.js', 'echarts.min.js'])

<div class="btn-group" role="group" aria-label="...">
    <button class="btn btn-default" onclick="update_data_by_ajax()">Update from Server</button>
    <span class="fileupload fileupload-new" data-provides="fileupload" style="margin-left: 3px">
        <span class="btn btn-default btn-file">
            <span class="fileupload">Upload Log Files</span>
            <input type="file" id="log_files" multiple="mutiple" />
        </span>
    </span>
</div>

<hr/>
<div id="main" style="width: 1000px;height:600px;"></div>

<script type="text/javascript">
    var myChart = echarts.init(document.getElementById('main'));

    function renderItem(params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = api.size([0, 1])[1] * 0.6;

        return {
            type: 'rect',
            shape: echarts.graphic.clipRectByRect({
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: height
            }, {
                    x: params.coordSys.x,
                    y: params.coordSys.y,
                    width: params.coordSys.width,
                    height: params.coordSys.height
                }),
            style: api.style()
        };
    };
    function seconds_to_str(val) {
        if (!val) {
            return '';
        }
        val = Math.round(val);
        var hr = Math.floor(val / 3600);
        var min = Math.floor((val - hr * 3600) / 60);
        var sec = val % 60;
        var s = '';
        if (hr) {
            s += hr + 'h';
        }
        if (hr == 0 && min == 0) {
            // don't show: 0mxxs
        } else {
            s += min + 'm';
        }
        if (sec) {
            s += sec + 's';
        }
        return s;
    }
    option = {
        tooltip: {
            formatter: function (params) {
                if (!params.value) {
                    return '';
                }
                var s = seconds_to_str(params.value[3]);
                return params.marker +
                    params.value[5] +
                    '<br/>count: ' + params.value[4] +
                    ', time : ' + s;
            },
        },
        title: {
            text: 'Cycle Time',
            left: 'center'
        },
        legend: {
            // TODO: why not show
            show: true,
            type: 'plain',
            align: 'left',
            data: [],
            formatter: function (name) {
                return 'Legend ' + name;
            }
        },
        dataZoom: [{
            type: 'slider',
            filterMode: 'weakFilter',
            showDataShadow: false,
            bottom: 15,
            height: 10,
            borderColor: 'transparent',
            backgroundColor: '#e2e2e2',
            labelFormatter: '',
            handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
            handleSize: 20,
            handleStyle: {
                shadowBlur: 6,
                shadowOffsetX: 1,
                shadowOffsetY: 2,
                shadowColor: '#aaa'
            }
        }, {
            type: 'inside',
            filterMode: 'weakFilter'
        }
        ],
        visualMap: {
            dimension: 3,
            min: 0,
            max: 500,
            // range: [10, 600], // 不设置 range，则 range 默认为 [min, max], 自动随 min max 而改变
            calculable: true,
            top: 50,
            right: 0,
            itemHeight: 500,
            formatter: function (value) {
                return seconds_to_str(value);
            }
        },
        xAxis: {
            min: 0,
            scale: true,
            minInterval: 60,
            axisLabel: {
                formatter: function (val) {
                    return seconds_to_str(val);
                }
            },
            splitLine: {
                show: true,
            },
            axisPointer: {
                type: 'line',
                show: true,
                label: {
                    show: true,
                    formatter: function (params) {
                        return seconds_to_str(params.value);
                    }
                }
            }
        },
        yAxis: {
            splitLine: {
                show: true,
            },
            axisPointer: {
                type: 'line',
                show: true,
                label: {
                    show: false
                }
            },
            data: []
        },
        series: [{
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
                normal: {
                    opacity: 0.8
                }
            },
            encode: {
                x: [1, 2],
                y: 0
            },
            data: [[0, 0, 0, 0]]
        }]
    };

    myChart.setOption(option);

    function update_data_by_ajax() {
        $.get('/ajax/log/summary')
            .done(function (data) {
                myChart.hideLoading();
                var mac_list = JSON.parse(data.mac_list);
                if (!mac_list) {
                    return;
                }
                reset_option();
                for (var idx = 0; idx < mac_list.length; idx++) {
                    update_data_of_mac(mac_list[idx], idx);
                }
            })
            .fail(function (data) {
                console.log('Error: ' + data);
            })
    }
    function update_data_of_mac(mac, idx) {
        $.get('/ajax/log/summary/' + mac)
            .done(function (data) {
                plan = JSON.parse(data.plan);
                if (plan == null) {
                    return;
                }
                set_data(plan, idx);
            })
            .fail(function (data) {
                console.log('Error: ' + data);
            });
    }
    function update_data_by_files(e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length) {
            return;
        }
        reset_option();
        for (var idx = 0; idx < files.length; idx++) {
            read_file(files[idx], idx);
        };
    }
    function read_file(file, idx) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var result = e.target.result;
            var data;
            if (result == 'data:') {
                data = '';
            } else {
                data = atob(result.split(';')[1].split(',')[1]);
            }
            var plan = build_plan_from_file(file.name, data);
            set_data(plan, idx);
        };
        reader.readAsDataURL(file);
    }
    function build_plan_from_file(file_name, content) {
        var plan = {};
        var file_name_a = file_name.split('-');
        while (file_name_a.length < 5) {
            file_name_a.push('');
        }
        plan.client = {};
        plan.client.rack = file_name_a[0];
        plan.client.location = file_name_a[1];
        var mac = file_name_a[2];
        var pxe = file_name_a[3];
        plan.count = parseInt(file_name_a[4]);
        var log = [];
        content.split('\n').forEach(function (line, li) {
            line = line.trim();
            if (line == '' || line[0] == '#') {
                return;
            }
            var line_a = line.split(',');
            log.push(
                {
                    count: line_a[0],
                    dt: parseInt(line_a[1]),
                    time: line_a[2],
                }
            )
        });
        plan.pxe_list = [];
        plan.pxe_list.push(
            {
                pxe: pxe,
                log: log
            }
        )
        return plan;
    }
    function reset_option() {
        option.visualMap.max = 0;
        option.legend.data = [];
        option.yAxis.data = []
        option.series[0].data = [];
    }
    function set_data(plan, idx) {
        var pxe_list = plan.pxe_list;
        var data = [];

        var baseTime = 0;
        var max_dt = 0;
        pxe_list.forEach(
            function (pxe) {
                data = data.concat(
                    pxe.log.map(
                        function (i) {
                            max_dt = Math.max(max_dt, i.dt);
                            return [
                                idx,
                                baseTime,
                                baseTime += i.dt,
                                i.dt,
                                i.count,
                                i.time
                            ];
                        }));
            });

        option.visualMap.max = Math.max(option.visualMap.max, max_dt);
        var legend = plan.client.rack + '/' + plan.client.location;
        option.legend.data[idx] = legend;
        option.yAxis.data[idx] = legend;
        option.series[0].data = option.series[0].data.concat(data);
        myChart.setOption(option);
    };
    $('#log_files')[0].addEventListener('change', update_data_by_files);
    update_data_by_ajax();
    // var timer = setInterval(update_data_by_ajax, 5000);
</script>